<template>
  <div>

    <el-link href="https://gitcode.com/xyxywan/audio-vue" target="_blank" type="primary">项目仓库</el-link>
    <br>
    <br>
    <br>
    <div
        ref="audioContainer"
        class="audio"
        :class="{'audio-off': !isMaximized}"
        @mouseenter="maximize"
        @mouseleave="onMouseLeave">
      <audio
          ref="audio"
          :src="audioInfo.src"
          preload="metadata"
          @ended="onSongEnded"
          @loadedmetadata="onMetadataLoaded"
          @timeupdate="updateTimeDisplay">
      </audio>
      <div class="audio-head">
        <div class="audio-head-tittle" :class="{'audio-head-tittle-off': !isMaximized}">
          <div ref="titleText" class="audio-head-tittle-text" :class="{'audio-head-tittle-text-off': isMaximized}">{{audioInfo.audioName}}</div>
        </div>
        <div class="audio-head-tittle-by" :class="{'audio-head-tittle-by-off': isMaximized}">{{audioInfo.author}}</div>
      </div>
      <div class="add"></div><!--  仅用于占位    -->
      <div ref="minTime" class="min-time" :class="{'min-time-off': isMaximized}"></div>
      <div class="audio-img">
        <canvas
            id="audio-img-canvas"
            :class="{'audio-img-canvas-on': isPlaying}"
            ref="canvas" height="200px" width="200px">
        </canvas>
        <div ref="coverImage" class="audio-img-cover" :class="{'audio-img-cover-off': !isMaximized}"></div>
        <canvas
            id="audio-img-canvas-play"
            ref="playCanvas"
            class="audio-img-canvas-play-off"
            :class="{'audio-img-canvas-play-on': isPlaying}"
            height="200px" width="45px"
            @click="togglePlay">

        </canvas>
      </div>
      <div class="audio-text">歌词功能待更新</div>
      <div class="audio-progress">
        <div
            ref="progressBar"
            class="audio-progress-all"
            @mouseenter="showProgressBtn=true"
            @mouseleave="showProgressBtn=false;progressDrag=false"
            @mousedown="startProgressDrag"
            @mousemove="handleProgressDrag"
            @mouseup="endProgressDrag">
          <span ref="progressNow" class="audio-progress-now"></span>
          <span ref="progressArt"  class="audio-progress-art" v-show="showProgressBtn"></span>
        </div>
        <div class="audio-by-text">
          <span class="audio-by-text-now">{{audioInfo.currentTimeText}}</span>
          <span class="audio-by-text-all">{{audioInfo.totalTimeText}}</span>
        </div>
      </div>
      <div class="audio-btn">
      <!--切换循环模式-->
        <div
            ref="listButton"
            :class="{ 'audio-btn-list-on': isLoop, 'audio-btn-list-off': !isLoop }"
            class="audio-btn-list"
            @click="toggleLoop">
        </div>
        <div class="audio-btn-before" @click="prevSong"></div>
        <div
            ref="playButton"
            class="audio-btn-play"
            :class="{'audio-btn-play-on': isPlaying, 'audio-btn-play-off': !isPlaying, 'audio-btn-play-off-a': !isMaximized}"
            @click="togglePlay">

        </div>
        <div class="audio-btn-sound" @click="toggleVolumeControl"></div>
        <div class="audio-btn-next" @click="nextSong"></div>
      </div>
      <div class="audio-sound"
          ref="volumeBar"
          :class="{ 'audio-sound-on': showVolumeBar}"
          @mouseleave="volumeDrag=false"
          @mousedown="startVolumeDrag"
          @mousemove="handleVolumeDrag"
          @mouseup="endVolumeDrag">
        <div class="audio-sound-all">
          <span ref="volumeNow" class="audio-sound-now"></span>
          <span ref="volumeArt" class="audio-sound-art"></span>
        </div>
      </div>

    </div>


    <a ref="titleOutText" class="audio-head-tittle-text-out"></a>
    <a ref="titleOutTextA" class="audio-head-tittle-text-out-a"></a>

    <br>
    <div style="width: 400px" v-for="(song, index) in this.songList">

      <span><el-button plain @click="switchSong(index)">{{ song.name + "  [" + formatSize(song.size)+ "]" }}  </el-button></span>

<!--      <el-button slot="reference" icon="Download" @click="downloadFile(song)"></el-button>-->

    </div>

  </div>
</template>

<script>
import axios from 'axios';
import "@/views/audio/audio.css"
export default {
  name: 'audio_vue', // 组件名称
  // 组件属性
  props: {
  },
  // 数据属性
  data() {
    return {
      isPlaying: false,
      isMaximized: false,
      showVolumeBar: false,
      currentIndex: 0,
      isLoop: false,
      progressDrag: false,
      volumeDrag: false,
      showProgressBtn: false,

      audioInfo: {
        src: null,
        audioName: null,
        author: null,
        currentTimeText: "00:00",
        totalTimeText: "00:00",
      },

      songList: [
      ],
      scrollPosition: 0,
      scrollSpeed: 1.8,

    }
  },

  // 计算属性
  computed: {
  },

  // 方法
  methods: {

// 加载当前歌曲
    loadSong() {
      this.updateSongInfo();
      this.$refs.progressNow.style.width = '0%';
      this.audioInfo.src = this.songList[this.currentIndex].url;
      this.$refs.audio.onerror = () => {
        console.error('音频加载失败');
        this.isPlaying = false;
      };
      if (this.isPlaying) {
        this.$nextTick(() => {
          console.log("play")
          this.$refs.audio.play();
        });
      }
    },



// 更新歌曲信息显示
    updateSongInfo() {
      let fileName = this.songList[this.currentIndex].name.split('.').slice(0, -1).join('.')
      const splitLastHyphen = s => {
        const i = s.lastIndexOf('-');
        return i >= 0 ? [s.slice(0, i), s.slice(i + 1)] : ['', s];
      };
      let currentSongInfo = splitLastHyphen(fileName);
      this.audioInfo.audioName = currentSongInfo[1];
      this.audioInfo.author = currentSongInfo[0];

      // this.$refs.titleOutText.textContent = this.audioInfo.audioName;
      // this.$refs.titleOutTextA.textContent = this.audioInfo.audioName;
      // this.scrollPosition = 0;
      // this.scrollSpeed = Math.abs(this.scrollSpeed);
    },

// 切换播放状态
    togglePlay() {
      if (this.$refs.audio.paused || this.$refs.audio.ended) {
        this.play();
      } else {
        this.pause();
      }
    },

// 播放
    play() {
      this.isPlaying = true;
      this.$refs.audio.play();
    },

// 暂停
    pause() {
      this.isPlaying = false;
      this.$refs.audio.pause();
    },

// 下一首
    nextSong() {
      this.currentIndex += 1;
      if (this.currentIndex >= this.songList.length) {
        this.currentIndex = 0;
      }
      this.loadSong();
    },

// 上一首
    prevSong() {
      this.currentIndex -= 1;
      if (this.currentIndex < 0) {
        this.currentIndex = this.songList.length - 1;
      }
      this.loadSong();
    },

// 切换循环模式
    toggleLoop() {
      this.isLoop = !this.isLoop;
    },

// 切换音量控制显示
    toggleVolumeControl() {
      this.showVolumeBar = !this.showVolumeBar;
    },

// 格式化时间显示
    formatTime(seconds) {
      let minutes = Math.floor(seconds / 60).toString().padStart(2, '0');
      let secs = Math.floor(seconds % 60).toString().padStart(2, '0');
      return `${minutes}:${secs}`;
    },

// 更新进度条
    updateProgress(e, flag=false) {
      // flag: 防止音频播放抖动，仅在松手时更新音乐的时间；拖动时只更新动画
      const progressRect = this.$refs.progressBar.getBoundingClientRect();
      let position = e.clientX - progressRect.left;
      let percentage = (position / progressRect.width) * 100;
      percentage = Math.max(0, Math.min(100, percentage));
      this.$refs.progressNow.style.width = `${percentage}%`;
      this.$refs.progressArt.style.left = `${percentage}%`;
      if(flag){
        this.$refs.audio.currentTime = (this.$refs.audio.duration * percentage) / 100;
      }
    },

// 开始拖动进度条
    startProgressDrag(e) {
      this.progressDrag = true;
    },
// 处理进度条拖动
    handleProgressDrag(e) {
      if (this.progressDrag) {
        this.updateProgress(e)
      }
    },

// 结束拖动进度条
    endProgressDrag(e) {
      if (this.progressDrag) {
        this.progressDrag = false;
        this.updateProgress(e, true);
      }
    },

// 设置音量
    setVolume(volume) {
      volume = Math.max(0, Math.min(1, volume));
      const percentage = volume * 100;
      this.$refs.volumeNow.style.width = `${percentage}%`;
      if (this.$refs.volumeArt) {
        this.$refs.volumeArt.style.left = `${percentage}%`;
      }
      this.$refs.audio.volume = volume;
    },

// 更新音量
    updateVolume(e) {
      const volumeRect = this.$refs.volumeBar.getBoundingClientRect();
      let position = e.clientX - volumeRect.left;
      let percentage = (position / volumeRect.width) * 100;

      percentage = Math.max(0, Math.min(100, percentage));
      this.setVolume(percentage / 100);
    },

// 开始拖动音量条
    startVolumeDrag(e) {
      this.volumeDrag = true;
      this.updateVolume(e);
    },

// 结束拖动音量条
    endVolumeDrag(e) {
      if (this.volumeDrag) {
        this.volumeDrag = false;
        this.updateVolume(e);
      }
    },

// 处理音量条拖动
    handleVolumeDrag(e) {
      if (this.volumeDrag) {
        this.updateVolume(e);
      }
    },

// 歌曲元数据加载完成
    onMetadataLoaded() {
      this.audioInfo.currentTimeText = this.formatTime(0);
      this.audioInfo.totalTimeText = this.formatTime(this.$refs.audio.duration);
    },

// 更新时间显示
    updateTimeDisplay() {
      const currentTime = this.$refs.audio.currentTime;
      const duration = this.$refs.audio.duration;
      const percent = (currentTime / duration) * 100;
      this.$refs.progressNow.style.width = `${percent}%`;
      this.$refs.progressArt.style.left = `${percent}%`;
      this.$refs.minTime.style.width = `${percent}%`;
      this.audioInfo.currentTimeText = this.formatTime(currentTime);
      // this.scrollText();
    },

// 滚动文本
    scrollText() {
      let textWidth, titleWidth;
      if (this.isMaximized) {
        textWidth = this.$refs.titleOutTextA.offsetWidth;
        titleWidth = this.$refs.titleText.offsetWidth;
      } else {
        textWidth = this.$refs.titleOutText.offsetWidth;
        titleWidth = this.$refs.titleText.offsetWidth;
      }
      if (textWidth > titleWidth) {
        const maxScroll = this.isMaximized ?
            -(textWidth - titleWidth + 20) :
            -(textWidth - titleWidth + 8);
        if (this.scrollPosition <= maxScroll || this.scrollPosition >= (this.isMaximized ? 20 : 8)) {
          this.scrollSpeed = -this.scrollSpeed;
        }
        this.scrollPosition -= this.scrollSpeed;
        this.$refs.titleText.style.textIndent = `${this.scrollPosition}px`;
      }
    },

// 歌曲结束
    onSongEnded() {
      if (!this.isLoop) {
        this.nextSong();
      } else {
        this.$refs.audio.currentTime = 0;
        this.$refs.audio.play();
      }
    },

// 切换最大化状态
    maximize() {
      this.isMaximized = true;
      this.$refs.titleText.style.textIndent = '0px';
      this.scrollPosition = 0;
      this.scrollSpeed = Math.abs(this.scrollSpeed);
    },

// 鼠标离开
    onMouseLeave() {
      this.isMaximized = false
      this.showVolumeBar = false;
    },

// 绘制音频画布
    drawAudioCanvas() {
      const ctx = this.$refs.canvas.getContext('2d');
      ctx.translate(100, 100);
      ctx.strokeStyle = 'rgba(255,255,255,1)';
      ctx.lineWidth = 6;
      ctx.arc(0, 0, 80, 0, Math.PI * 2, true);
      ctx.stroke();
      ctx.beginPath();
      ctx.lineWidth = 3;
      ctx.arc(0, 0, 72, Math.PI / 6, Math.PI / 6 * 4, false);
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(0, 0, 72, Math.PI / 6 * 9, Math.PI / 6 * 6, true);
      ctx.stroke();
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.arc(0, 0, 50, Math.PI / 6 * 9, Math.PI / 6 * 11, true);
      ctx.stroke();
    },

// 绘制播放图标
    drawPlayIcon() {
      const ctx = this.$refs.playCanvas.getContext('2d');
      ctx.translate(25, 10);
      ctx.lineWidth = 4;
      ctx.strokeStyle = 'rgba(255,255,255,1)';
      ctx.rect(-10, 0, 20, 20);
      ctx.stroke();
      ctx.beginPath();
      ctx.rect(-10, 20, 20, 10);
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(0, 30);
      ctx.lineTo(0, 140);
      ctx.stroke();
      ctx.beginPath();
      ctx.translate(0, 140);
      ctx.rotate(120 * Math.PI / 180);
      ctx.rect(0, 0, 18, 32);
      ctx.stroke();
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.moveTo(10, 25);
      ctx.lineTo(30, 25);
      ctx.stroke();
    },

    async fetchFileList() {
      try {
        const response = await axios.get('http://iou.ink/file/');
        this.songList = response.data.files;
        console.log(response.data.files);
      } catch (error) {
        console.error('获取文件列表失败:', error);
        this.error = '获取文件列表失败，请稍后重试';
      } finally {
      }
    },
    formatSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    switchSong(index){
      this.currentIndex = index;
      this.loadSong();
    },
    downloadFile(song) {
      // 方法1：直接创建 <a> 标签下载
      const link = document.createElement('a');
      link.href = song.url; // public 下的路径
      link.download = song.name; // 可选：设置下载的文件名
      link.click();
    }

  },

  created() {
  },
  mounted() {
    this.fetchFileList().then(ret => {

      this.drawAudioCanvas()  // 绘制唱片图像
      this.drawPlayIcon() // 绘制唱臂图像
      this.updateSongInfo();  // 初始的歌曲文本信息
      this.setVolume(this.$refs.audio.volume);  // 设置初始的音量条位置
      this.audioInfo.src = this.songList[this.currentIndex].url;
    })

  }
}

</script>

<style scoped>

</style>